<template>
    <div class="cart-submit-bar">
        <van-checkbox v-model="checkedAll">全选</van-checkbox>
        <van-button round plain type="danger" size="small" :loading="deleteLoading"
                    @click="handleRemoveItems" v-if="manage">
            删除
        </van-button>
        <div class="cart-submit-bar-checkout" v-else>
            <div class="cart-submit-bar-content">
                <span>合计:</span>
                <price :value="totalPrice" :size="16"/>
            </div>
            <van-button class="cart-submit-bar__button--danger" round type="danger"
                        :loading="checkoutLoading"
                        :disabled="checkedSize === 0"
                        @click="handleCheckout">
                结算({{checkedSize}})
            </van-button>
        </div>
    </div>
</template>

<script>
  import * as _ from "lodash"
  import { Button, Checkbox, Dialog, Toast } from "vant"
  import { createNamespacedHelpers } from "vuex"
  import Price from "@/components/Price"
  import { checkout, message, order } from "@mall/api-services"

  const { mapState, mapActions, mapGetters } = createNamespacedHelpers("cart")

  export default {
    name: "CartSubmitBar",
    components: {
      Price,
      [Button.name]: Button,
      [Checkbox.name]: Checkbox,
    },
    props: {
      totalCount: Number,
      manage: Boolean,
    },
    computed: {
      ...mapState(["id", "items"]),
      ...mapGetters(["checkedSize", "checkedItems", "totalPrice"]),
      emptyItems() {
        return _.isEmpty(this.items)
      },
      checkedAll: {
        get: function() {
          const { items } = this
          for (const item of items) {
            if (!item.checked) {
              return false
            }
          }
          return !this.emptyItems
        },
        set: function(checked) {
          if (this.emptyItems) {
            return
          }
          const { checkAllItems, uncheckAllItems } = this
          Toast.loading()
          new Promise((resolve, reject) => {
            if (checked) {
              checkAllItems().then(resolve).catch(reject)
            } else {
              uncheckAllItems().then(resolve).catch(reject)
            }
          }).finally(() => Toast.clear())
        },
      },
    },
    data() {
      return {
        checkoutLoading: false,
        deleteLoading: false,
      }
    },
    methods: {
      ...mapActions(["checkAllItems", "uncheckAllItems", "removeItems"]),
      handleCheckout() {
        const { id, checkedItems } = this
        if (_.isEmpty(checkedItems)) {
          Toast("你还没有选择商品哦")
          return
        }

        this.checkoutLoading = true
        const aCheckout = new checkout.Checkout()
        aCheckout.items = checkedItems
        aCheckout.cartId = id
        aCheckout.source = order.OrderSource.Browser
        checkout.CheckoutServiceV1.createCheckout(aCheckout)
          .then(checkout => this.$router.push(`/checkouts/${checkout.id}`))
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
          .finally(() => this.checkoutLoading = false)
      },
      handleRemoveItems() {
        const { checkedItems, checkedSize } = this
        if (_.isEmpty(checkedItems)) {
          Toast("你还没有选择商品哦")
          return
        }

        Dialog.confirm({
          message: `确定要删除这${checkedSize}个商品吗？`,
        })
          .then(() => {
            const itemIds = _.map(checkedItems, aItem => aItem.id)
            this.deleteLoading = true
            this.removeItems(itemIds)
              .then(() => Toast("删除成功"))
              .finally(() => this.deleteLoading = false)
          })
      },
    },
  }
</script>

<style lang="scss" scoped>
    .cart-submit-bar {
        position: fixed;
        bottom: 50px;
        left: 0;
        background: #fff;
        height: 50px;
        width: 100%;
        padding: 0 9px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .cart-submit-bar-checkout {
            flex: 1;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .cart-submit-bar-content {
                flex: 1;
                height: 1em;
                line-height: 1em;
                padding: 0 12px;
            }

            .cart-submit-bar__button--danger {
                height: 40px;
                width: 90px;
            }
        }
    }
</style>
